<!--
Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.

> Licensed under the Apache License, Version 2.0 (the "License");
> you may not use this file except in compliance with the License.
> You may obtain a copy of the License at

>     http://www.apache.org/licenses/LICENSE-2.0

> Unless required by applicable law or agreed to in writing, software
> distributed under the License is distributed on an "AS IS" BASIS,
> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> See the License for the specific language governing permissions and
> limitations under the License.
-->

<!DOCTYPE html>
<html>
<head>
  <title>h5 demo</title>
  <meta charset="utf-8" />
  <meta name="viewport"
        content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" />
  <style>
    html,
    body {
      margin: 0;
      padding: 0;
      height: 100%;
    }
    .container {
      width: 100%;
      height: 100%;
      background: black;
    }
    .loading {
      width: 50px;
      height: 50px;
      position: absolute;
      top: calc(50% - 25px);
      left: calc(50% - 25px);
      -ms-animation: load-anim 2s linear infinite;
      -webkit-animation: load-anim 2s linear infinite;
      -moz-animation: load-anim 2s linear infinite;
      -webkit-animation: load-anim 2s linear infinite;
      -o-animation: load-anim 2s linear infinite;
      animation: load-anim 2s linear infinite;
    }
    @keyframes load-anim {
      from {
        -ms-transform: rotate(0deg);
        -moz-transform: rotate(0deg);
        -webkit-transform: rotate(0deg);
        -o-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -ms-transform: rotate(360deg);
        -moz-transform: rotate(360deg);
        -webkit-transform: rotate(360deg);
        -o-transform: rotate(360deg);
        transform: rotate(360deg);
      }
    }
    #network-info {
      pointer-events: none;
      position: absolute;
      top: 0px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      width: 100%;
      color: #3AC295;
    }
    #keyboard-dialog {
      border: 1px solid lightblue;
      border-radius: 10px;
    }
    .play-ctr-btn {
      display: inline-block;
      background: #fff;
      border: 1px solid #595959;
      text-align: center;
      height: 30px;
      line-height: 30px;
      border-radius: 5px;
      font-size: 14px;
    }
    .message-modal, .exit-modal {
      display: none;
      width: 300px;
      height: 200px;
      position: absolute;
      z-index: 999;
      top: 50%;
      left: 50%;
      background-color: #fff;
      border: 1px solid #dfe1e6;
      border-radius: 5px;
      transform: translate(-50%, -50%);
    }
    .header-content {
      position: fixed;
      top: 0px;
      text-align: center;
      font-size: 16px;
      height: 20%;
      width: 100%;
    }
    .body-content {
      text-align: center;
      height: 40%;
      margin-top: 20%;
    }
    .footer-content {
      height: 20%;
      border-top: 1px solid #dfe1e6;
      display: flex;
      justify-content: space-around;
      position: fixed;
      bottom: 0;
      width: 100%;
    }
    .button-alone {
      width: 100%;
      height: 100%;
      border: none;
      text-align: center;
      background-color: #fff;
    }
    .control-btn {
      display: none;
      user-select: none;
      font-size: 14px;
      line-height: 40px;
      text-align: center;
      width: 40px;
      height: 40px;
      position: fixed;
      z-index: 999;
      top: 15%;
      left: 35%;
      background-color: #fff;
      border: 1px solid #dfe1e6;
      border-radius: 50%;
      background-image: url(./images/ctrl_view.png);
      background-size: 42px;
      background-position: center;
    }
    .button-modal{
      display: none;
      width: 255px;
      height: 175px;
      position: absolute;
      z-index: 999;
      top: 50%;
      left: 50%;
      background-color: rgba(0, 0, 0, 0.4);
      border-radius: 5px;
      transform: translate(-50%, -50%);
    }
    .button-list {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;
      margin-bottom: 15px;
      font-size: 15px;
    }
    .button-network, .button-fullscreen {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 45px;
    }
    .button-network, .button-fullscreen, .button-exit, .fullscreen-btn {
      width: 42%;
      height: 41px;
      line-height: 41px;
      text-align: center;
      padding: 1px 5px;
      background-color: #eee;
    }
    .back-btn, .home-btn, .list-btn{
      width: 31%;
      height: 41px;
    }
    .radio-group {
      color: #ffffff;
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 55px;
      font-size: 15px;
    }
    input[type="radio"] {
      transform: scale(1.5);
      accent-color: #85090c;
    }
    .exit-btn, .trust-btn {
      border-top: none;
      border-left: none;
      border-bottom: none;
      border-right: 1px solid #dfe1e6;
    }
    .exit-btn, .cancel-btn {
      width: 50%;
      height: 100%;
      text-align: center;
      background-color: #fff;
    }
    .trust-btn {
      width: 100%;
      height: 100%;
      text-align: center;
      background-color: #fff;
    }
    .cancel-btn {
      border: none;
    }
    #mobileNetworkDelay {
      display: none;
      position: absolute;
      left: 0;
      top: 0;
      width: 40px;
      height: 40px;
      text-align: center;
      color: #3AC295;
      z-index: 999;
    }
    .slider {
      position: relative;
      width: 35px;
      height: 15px;
      border-radius: 20px;
      background-color: #ccc;
    }
    .slider-btn {
      position: absolute;
      left: 0;
      top: -2.5px;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background-color: #fff;
      box-sizing: border-box;
    }
    .pc-button-list {
      height: 20%;
      width: 100%;
      display: none;
      justify-content: flex-start;
      flex-direction: column;
      align-items: center;
    }
    .clarity-btn, .normal-btn {
      width: 25%;
      overflow: hidden;
    }
    .clarity-btn {
      margin-top: 25px;
    }
    .pc-button-list button {
      width: 90px;
      height: 40px;
      background-color: #fff;
      border: 1px solid #ccc;
    }
    .normal-btn {
      margin-top: 10px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 40px;
      font-size: 15px;
    }
    .radio-group-pc {
      color: #595959;
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 40px;
      font-size: 15px;
    }
    .pc-slider-btn {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .mr-left-10 {
      margin-left: 10px;
    }
    .pc-color {
      background-color: #eee;
    }
    #pcNetworkContent {
      display: none;
    }
    .trust-msg {
      margin: 0px;
      text-align: left;
      font-size: 14px;
      text-indent: 2em;
    }
  </style>
</head>

<body onunload="cloudapp.exit()">
<div id="fullscreen-container"
     class="fullscreen-container">
  <div id="container"
       class="broadway container"
       workers="false"
       render="true"
       webgl="auto">
    <div class="loading"
         id="loading">
      <svg xmlns="http://www.w3.org/2000/svg"
           width="50"
           height="50">
        <path fill="#909090"
              d="M22.5 2h5v11h-5z" />
        <path fill="#B0B0B0"
              d="M6.97 10.504l3.535-3.535 7.778 7.778-3.536 3.535z" />
        <path fill="silver"
              d="M2 22.5h11v5H2z" />
        <path fill="#D0D0D0"
              d="M10.504 43.03l-3.535-3.535 7.779-7.777 3.535 3.536z" />
        <path fill="#303030"
              d="M22.5 37h5v11h-5z" />
        <path fill="#505050"
              d="M43.03 39.497l-3.535 3.533-7.776-7.78 3.536-3.534z" />
        <path fill="#707070"
              d="M37 22.5h11v5H37z" />
        <path fill="#909090"
              d="M39.496 6.969l3.535 3.536-7.78 7.777-3.534-3.536z" />
      </svg>
    </div>
    <div id="network-info" class="extra-ui">
      <div id="pcNetworkContent">
        时延 <span id="pcNetworkDelay"></span>ms
      </div>
    </div>
    <div class="message-modal extra-ui" id="messageModal">
      <div class="header-content">
        <p>温馨提示</p>
      </div>
      <div class="body-content">
        <p class="msg" id="msgContent"></p>
      </div>
      <div class="footer-content">
        <button class="button-alone" onclick="closeModal()">退出</button>
      </div>
    </div>
    <div class="exit-modal extra-ui" id="exitModal">
      <div class="header-content">
        <p>温馨提示</p>
      </div>
      <div class="body-content">
        <p class="msg" id="msgContent">确定退出吗？</p>
      </div>
      <div class="footer-content">
        <button class="exit-btn" onclick="exitPhone()">退出</button>
        <button class="cancel-btn" onclick="closeExitModal()">取消</button>
      </div>
    </div>
    <div id="controlBtn" class="control-btn extra-ui">
      <span id="mobileNetworkDelay"></span>
    </div>
    <div id="buttonModal" class="button-modal extra-ui">
      <div class="radio-group">
        <div class="UHD">
          <input type="radio" name="clarity" id="UHD" value="UHD" onchange="radioChange(event)">
          <label for="UHD">超清</label>
        </div>
        <div class="HD">
          <input type="radio" name="clarity" id="HD" value="HD" checked="true" onchange="radioChange(event)">
          <label for="HD">高清</label>
        </div>
        <div class="SD">
          <input type="radio" name="clarity" id="SD" value="SD" onchange="radioChange(event)">
          <label for="SD">流畅</label>
        </div>
      </div>
      <div class="button-list">
        <div class="button-network">
          <div>时延</div>
          <div class="slider" id="networkSlider">
            <div class="slider-btn" id="networkSliderBtn"></div>
          </div>
        </div>
        <div class="button-fullscreen" id="buttonFullscreen">
          <div>全屏</div>
          <div class="slider" id="toggleFullscreen">
            <div class="slider-btn" id="fullscreenSliderBtn"></div>
          </div>
        </div>
        <div class="button-exit" id="exitBtn" onclick="showExitModal()">退出云手机</div>
      </div>
      <div class="button-list">
        <button class="back-btn" id="backBtn" onclick="sendKeyCodeBack()">返回</button>
        <button class="home-btn" id="homeBtn" onclick="sendKeyCodeHome()">桌面</button>
        <button class="list-btn" id="listBtn" onclick="sendKeyCodeMenu()">多任务</button>
      </div>
    </div>
  </div>

  <div class="message-modal" id="trustModal">
    <div class="header-content">
      <p>信任目标机器</p>
    </div>
    <div class="body-content">
      <p class="trust-msg">首次接入需点击下方信任按钮进行信任。</p>
      <p class="trust-msg" id="mobileMsg">待信任页面停止刷新后，返回上一个页面。</p>
      <p class="trust-msg" id="pcMsg">在新页签中依次点击高级、继续前往，待页面停止刷新后，关闭信任页面。</p>
    </div>
    <div class="footer-content">
      <button id="trustBtn" class="trust-btn" onclick="trustHost()">信任</button>
    </div>
  </div>
</div>
<div class="pc-button-list extra-ui" id="pcButtonList">
  <div class="clarity-btn">
    <div class="radio-group-pc">
      <div class="UHD">
        <input type="radio" name="clarityPc" id="PCUHD" value="UHD" onchange="radioChange(event)">
        <label for="PCUHD">超清</label>
      </div>
      <div class="HD">
        <input type="radio" name="clarityPc" id="PCHD" value="HD" checked onchange="radioChange(event)">
        <label for="PCHD">高清</label>
      </div>
      <div class="SD">
        <input type="radio" name="clarityPc" id="PCSD" value="SD" onchange="radioChange(event)">
        <label for="PCSD">流畅</label>
      </div>
      <div class="pc-slider-btn">
        <div class="slider" id="pcNetworkSlider">
          <div class="slider-btn pc-color" id="pcNetworkSliderBtn"></div>
        </div>
        <div class="mr-left-10">时延</div>
      </div>
    </div>
  </div>
  <div class="normal-btn">
    <button onclick="sendKeyCodeBack()">返回</button>
    <button onclick="sendKeyCodeHome()">桌面</button>
    <button onclick="sendKeyCodeMenu()">多任务</button>
    <button onclick="showExitModal()">退出云手机</button>
  </div>
</div>
<script src="./common.js"></script>
<script type="text/javascript">
  var _HTTP_MODE_ = false;
  var _EXTRA_UI_ = true;
  var phoneId = null;
  var sessionId = null;
  var token = null;
  var commonLibPath = null;
  var isUserLogin = false;
  var cloudapp = null;
  
  sessionStorage.setItem('isFirstTrust', 'false');
  window.onload = function () {
    let getConfig = {
      get basePath() {
        let path = window.location.origin;
        let pathname = window.location.pathname;
        let demoIdx = pathname.lastIndexOf('/demo');
        let indexIdx = pathname.lastIndexOf('/index');
        if (demoIdx !== -1) {
          return path + pathname.substr(0, demoIdx);
        } else if (indexIdx !== -1) {
          return path + pathname.substr(0, indexIdx);
        } else {
          return path;
        }
      },
      get libPath() {
        return this.basePath + '/lib/'
      }
    };
    commonLibPath = getConfig.libPath;

    // 从url中获取ip和port
    var urlParams = new URLSearchParams(window.location.search);
    var urlIp = urlParams.get('ip');
    var urlPort = urlParams.get('port');
    phoneId = urlParams.get('phone_id');
    sessionId = urlParams.get('session_id');
    token = urlParams.get('token');
    if (phoneId) {
      // APP调度系统连接
      getInterfaceDomain();
    } else {
      if (urlIp && urlPort) {
        // APP测试直连
        let hostConfig = {
          ip: urlIp,
          port: urlPort
        };
        sessionStorage.setItem('cloudPhoneHost', JSON.stringify(hostConfig));
        sessionStorage.setItem('channelType', 'WebSocket');
        connectCloudPhone();
      } else {
        // H5调度系统连接 && H5测试直连
        connectCloudPhone();
      }
    }

    if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
      document.getElementById('mobileMsg').style.display = 'block';
      document.getElementById('pcMsg').style.display = 'none';
    } else {
      document.getElementById('pcMsg').style.display = 'block';
      document.getElementById('mobileMsg').style.display = 'none';
    }
  }

  function uuid_32() {
    let uuid = '';
    for(i = 0; i < 26; i++) {
      uuid += Math.floor(Math.random()*10)
    }
    return uuid + '32uuid'
  }

  function connectCloudPhone() {
    var cloudPhoneHost = JSON.parse(sessionStorage.getItem('cloudPhoneHost'));
    var phoneInfo = JSON.parse(sessionStorage.getItem('phoneInfo'));
    var channelType = sessionStorage.getItem('channelType');
    if (cloudPhoneHost) {
      isUserLogin = false;
      // 测试直连
      var cloudIp = cloudPhoneHost['ip'];
      var cloudPort = cloudPhoneHost['port'];
      var cloudPhoneParams = {
        ip: cloudIp,
        port: cloudPort,
        session_id: uuid_32(),
        background_timeout: '60',
        available_playtime: '6000',
        touch_timeout: 600,
        connect_uri: (_HTTP_MODE_ ? 'ws://' : 'wss://') + [cloudIp, cloudPort].join(':')
      };
    } else if (phoneInfo) {
      // 调度系统
      isUserLogin = true;
      var cloudIp = phoneInfo['ip'];
      var cloudPort = phoneInfo['port'];
      var cloudPhoneParams = {
        ip: cloudIp,
        port: cloudPort,
        session_id: phoneInfo['session_id'],
        background_timeout: phoneInfo['background_timeout'],
        available_playtime: phoneInfo['available_playTime'],
        touch_timeout: phoneInfo['touch_timeout'],
        connect_uri: (_HTTP_MODE_ ? 'ws://' : 'wss://') + [cloudIp, cloudPort].join(':'),
      };
    } else {
      let localHref = window.location.href;
      if (localHref.indexOf('demo.html') > -1) {
        localHref = window.location.href.replace('demo.html', 'enter.html');
      } else {
        localHref = window.location.href.replace('index', '');
      }

      window.location.href = localHref;
    }

    var params = {
      ...cloudPhoneParams,
      channelType: channelType,
      ticket: '256random'.padStart(256, '0'),
      aes_key: '11111111111111111111111111111111',
      auth_ts: new Date().getTime(),
      _debug: true,
      auto_rotate: true,
      libPath: commonLibPath, // 配置库文件地址
      microPhoneOutputType: 'OPUS', // PCM或OPUS
      keepRatio: false // 保持宽高比
    };
    try {
      if (CloudApp.isSupport()) {
        cloudapp = new CloudApp("container", params);
        cloudapp.on("appStateChange", function (event, data) {
          console.log(event, data);
          var state = data && data.state;
          var STATE_CONFIG = {
            STARTED: 2048,
            RESUMED: 5120,
            MEDIA_CONFIG_SUCCESS: 8448,
            RETRY_SUCCESS: 3072,
            BACK_HOME: 6400,
          };

          var normalStates = [
            STATE_CONFIG.STARTED,
            STATE_CONFIG.RESUMED,
            STATE_CONFIG.MEDIA_CONFIG_SUCCESS,
            STATE_CONFIG.BACK_HOME,
            STATE_CONFIG.RETRY_SUCCESS,
          ];
          document.getElementById("loading").style.display = normalStates.includes(state) ? 'none' : 'block';
          showAlertModal(data);
          startsuccessCallBack(data);

          if(state === STATE_CONFIG.RESUMED) {
            cloudapp.requestIFrame();
          }
        });

        cloudapp.on("netStateChange", function (event, data) {
          if (!_EXTRA_UI_) {
            return;
          }
          let delayElement = null;
          if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
            delayElement = document.getElementById('mobileNetworkDelay');
          } else {
            delayElement = document.getElementById('pcNetworkDelay');
          }
          delayElement.innerHTML = data.delay;
        });

        // 时延开关
        toggleNetworkInfo();

        // 音量设置，范围为 0 ~ 100
        cloudapp.setVolume(60);

        cloudapp.on("audioStateChange", function (event, data) {
          console.log(event, data);
        });

        cloudapp.on("cloudAppData", function (event, data) {
          var typedArray = new Uint8Array(data);
          var str = decodeUTF8(typedArray);
          console.log(event, str)
        });

        window.cloudapp = cloudapp;
        window.sendDataToCloudApp = function (str) {
          var utf8Array = encodeUTF8(str);
          var typedArray = new Uint8Array(utf8Array);
          window.cloudapp.sendDataToCloudApp(typedArray.buffer);
        };

        listenLocationReload();

        // 监听云机复制内容写入端侧粘贴板
        cloudapp.on("clipboardDataChange", function (event, data) {
          var save = function(e) {
            e.clipboardData.setData('text/plain', data);
            e.preventDefault();
          }
          document.addEventListener('copy', save);
          document.execCommand('copy');
          document.removeEventListener('copy',save);
        });

        // 监听端侧粘贴，获取粘贴板内容发给云机
        document.addEventListener('paste', (event) => {
            const pasteContent = event.clipboardData.getData('text/plain');
            cloudapp.sendClipboardData(pasteContent);
        });
      }
    } catch (e) {
      console.log(e);
    }
  }

  function getInterfaceDomain() {
    isUserLogin = true;
    let currentHref = window.location.href;
    let jsonFilePath = null;
    if (currentHref.indexOf('index') > -1) {
      jsonFilePath = currentHref.replace('index', 'common.json');
    } else {
      jsonFilePath = currentHref.replace('demo.html', 'common.json');
    }

    xhrHttpRequest('GET', jsonFilePath, null).then((res) => {
      commonParams = JSON.parse(res);
      getPhoneInfo();
    }, error => {
      showResErrorMsg(error);
    });
  }

  function getPhoneInfo() {
    const allocateUrl = [commonParams.interfaceDomain, 'connection/allocate'].join('/');
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    const params = JSON.stringify({
      'phone_id': phoneId,
      'client_type': 'HTML5'
    });
    const headerConfig = {
      'token': token || userInfo.token,
      'session_id': sessionId || userInfo.session_id
    };
    xhrHttpRequest('POST', allocateUrl, params, headerConfig).then((res) => {
      sessionStorage.setItem('phoneInfo', res);
      sessionStorage.setItem('channelType', 'WebSocket');
      const targetStr = res && [JSON.parse(res).ip, JSON.parse(res).port].join(':');
      showTrustModal(targetStr);
    }, error => {
      if (!_EXTRA_UI_) {
        return
      }
      const errorMsg = error && JSON.parse(error).errorMsg;
      const modalEle = document.getElementById('messageModal');
      const msgEle = document.getElementById('msgContent');
      msgEle.innerText = errorMsg;
      modalEle.style.display = 'block';
    });
  }

  function toggleNetworkInfo() {
    if (!_EXTRA_UI_) {
      return
    }
    let networkInfoElement = null;
    let sliderEle = null;
    let sliderBtnEle = null;
    let sliderBtnBg = null;
    if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
      networkInfoElement = document.getElementById('mobileNetworkDelay');
      sliderEle = document.getElementById('networkSlider');
      sliderBtnEle = document.getElementById('networkSliderBtn');
      sliderBtnBg = '#fff';
    } else {
      networkInfoElement = document.getElementById('pcNetworkContent');
      sliderEle = document.getElementById('pcNetworkSlider');
      sliderBtnEle = document.getElementById('pcNetworkSliderBtn');
      sliderBtnBg = '#eee';
    }
    
    sliderEle.addEventListener('click', () => {
      const left = sliderBtnEle.offsetLeft;
      if (left === 0) {
        sliderBtnEle.style.left = '15px';
        sliderEle.style.backgroundColor = '#a17c7f';
        sliderBtnEle.style.backgroundColor = '#85090c';
        networkInfoElement.style.display = 'inline-block';
      } else {
        sliderBtnEle.style.left = '0px';
        sliderEle.style.backgroundColor = '#ccc';
        sliderBtnEle.style.backgroundColor = sliderBtnBg;
        networkInfoElement.style.display = 'none';
      }
    });
  }

  function showExitModal() {
    if (!_EXTRA_UI_) {
      return
    }
    const buttonModalEle = document.getElementById('buttonModal');
    const exitModalEle = document.getElementById('exitModal');
    buttonModalEle.style.display = 'none';
    exitModal.style.display = 'block';
  }

  function exitPhone() {
    exit();
    closeExitModal();
  }

  function closeExitModal() {
    if (!_EXTRA_UI_) {
      return
    }
    const exitModalEle = document.getElementById('exitModal');
    exitModal.style.display = 'none';
  }

  function exit() {
    cloudapp.exit();
    if (_EXTRA_UI_) {
      var networkInfoElement = document.getElementById('mobileNetworkDelay');
      networkInfoElement.hidden = true;
    }

    let isAppUse = false;
    try {
      CasCallback.exit();
      isAppUse = true;
    } catch (error) {
      isAppUse = false;
    }

    if (!isAppUse) {
      sessionStorage.removeItem('cloudPhoneHost');
      sessionStorage.removeItem('phoneInfo');
      sessionStorage.removeItem('rtcConfig');
      let currentUrl = window.location.href;
      if (currentUrl.indexOf('demo.html') > -1) {
        currentUrl = currentUrl.replace('demo.html', isUserLogin ? 'phone.html' : 'enter.html');
      } else {
        currentUrl = currentUrl.replace('index', 'phone');
      }

      const paramsIdx = currentUrl.indexOf('?');
      if (paramsIdx > -1) {
        currentUrl = currentUrl.slice(0, paramsIdx);
      }
      window.location.href = currentUrl;
    }
  }

  function fullscreenToggle(fullscreenEle) {
    cloudapp.fullscreenToggle(fullscreenEle);
    console.log("Is in fullscreen?", cloudapp.isFullscreen());
  }

  function sendKeyCodeBack() {
    cloudapp.back();
  }

  function sendKeyCodeHome() {
    cloudapp.home();
    const buttonModalEle = document.getElementById('buttonModal');
    buttonModalEle.style.display = 'none';
  }

  function sendKeyCodeMenu() {
    cloudapp.menu();
    const buttonModalEle = document.getElementById('buttonModal');
    buttonModalEle.style.display = 'none';
  }

  function setResolution() {
    var dom = document.getElementById('resolution');
    if (!dom) {
      return;
    }
    var resolution = dom.options[dom.selectedIndex || 0].value;
    cloudapp.setResolution(CloudApp.RESOLUTIONS[resolution]);
  }

  function encodeUTF8(textStr) {
    var encodedStr = encodeURIComponent(textStr);
    var encodedArray = [];
    for (var i = 0; i < encodedStr.length; i++) {
      var cur = encodedStr.charAt(i);
      if (cur === '%') {
        var code = encodedStr.charAt(i + 1) + encodedStr.charAt(i + 2);
        encodedArray.push(parseInt(code, 16));
        i += 2;
      } else {
        encodedArray.push(cur.charCodeAt(0));
      }
    }

    return encodedArray;
  }

  function decodeUTF8(utf8Array, start, end) {
    var len = utf8Array.length;
    start = start || 0;
    end = end || len;
    if (start < 0 || start >= len || end < 0 || end > len) {
      return '';
    }

    var encodedStr = '';
    for (var i = start; i < end; i++) {
      encodedStr += '%' + utf8Array[i].toString(16);
    }

    return decodeURIComponent(encodedStr);
  }

  function showAlertModal(data) {
    if (!_EXTRA_UI_) {
      return
    }
    const modalEle = document.getElementById('messageModal');
    const msgEle = document.getElementById('msgContent');
    const startSuccessState = 512;
    // 连接成功需要关闭已显示的弹框
    if (data.state === startSuccessState) {
      if(modalEle.style.display === 'block') {
        modalEle.style.display = 'none';
        return;
      }
    }
    if (data.tip) {
      msgEle.innerHTML = data.tip;
      modalEle.style.display = 'block';
    }
  }

  function closeModal() {
    const modalEle = document.getElementById('messageModal');
    modalEle.style.display = 'none';
    if (cloudapp) {
      exit();
    }
  }

  function startsuccessCallBack(data){
    const connectSuccessState = 2048;
    if (data.state === connectSuccessState) {
      if (_EXTRA_UI_) {
        if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
          closeCtrlModal();
        } else {
          let pcOperateBtn = document.getElementById('pcButtonList');
          pcOperateBtn.style.display = 'flex';
        }
      }
      
      try {
        CasCallback.startSuccessCallback();
      } catch (error) {}
    }
  }

  function radioChange(event) {
    const checkedVal = event && event.target.value;
    cloudapp.setResolution(checkedVal);
  }

  function closeCtrlModal() {
    const ctrlEle = document.getElementById('controlBtn');
    const buttonModalEle = document.getElementById('buttonModal');
    const playContainer = document.querySelector('article');
    const playerElement = playContainer.shadowRoot.querySelector('#playCanvas') || playContainer.shadowRoot.querySelector('#phoenixVideo');
    const fullscreenBtn = document.getElementById('buttonFullscreen');
    ctrlEle.style.display = 'block';
    ctrlEle.addEventListener('click', (event) => {
      if(buttonModalEle.style.display !== 'block') {
        buttonModalEle.style.display = 'block';
      } else {
        buttonModalEle.style.display = 'none';
      }
    });

    if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
      fullscreenBtn.style.display = 'flex';
      playerElement.addEventListener('touchend', (event) => {
        if(!buttonModalEle.contains(event.target) && !ctrlEle.contains(event.target)) {
          buttonModalEle.style.display = 'none';
        }
      });
    } else {
      fullscreenBtn.style.display = 'none';
      document.addEventListener('click', (event) => {
        if(!buttonModalEle.contains(event.target) && !ctrlEle.contains(event.target)) {
          buttonModalEle.style.display = 'none';
        }
      });
    }

    buttonModalEle.addEventListener('click', (event) => {
      event.stopPropagation();
    });
  }

  function trustHost() {
    const phoneInfo = JSON.parse(sessionStorage.getItem('phoneInfo'));
    const ipVal = phoneInfo.ip;
    const portVal = phoneInfo.port;
    window.open('https://' + [ipVal, portVal].join(':'), '_black');

    const targetStr = [ipVal, portVal].join(':');
    storageTrustTarget(targetStr);
    setTimeout(() => {
      closeTrustModal();
      connectCloudPhone();
    }, 2000);
  }

  function showTrustModal(targetStr) {
    sessionStorage.setItem('isFirstTrust', 'false');
    const trustTargetStr = sessionStorage.getItem('trustTargetList');
    let openModal = false;
    if (trustTargetStr) {
      const trustTargetList = JSON.parse(trustTargetStr);
      if (trustTargetList.includes(targetStr)) {
        openModal = false;
      } else {
        sessionStorage.setItem('isFirstTrust', 'true');
        openModal = true;
      }
    } else {
      sessionStorage.setItem('isFirstTrust', 'true');
      openModal = true;
    }

    if (openModal && !_HTTP_MODE_) {
      const trustModal = document.getElementById('trustModal');
      trustModal.style.display = 'block';
      return;
    }

    connectCloudPhone();
  }

  function storageTrustTarget(targetStr) {
    const trustTargetStr = sessionStorage.getItem('trustTargetList');
    if (trustTargetStr) {
      const trustTargetList = JSON.parse(trustTargetStr);
      trustTargetList.push(targetStr);
      sessionStorage.removeItem('trustTargetList');
      sessionStorage.setItem('trustTargetList', JSON.stringify(trustTargetList));
    } else {
      const trustTargetList = [targetStr];
      sessionStorage.setItem('trustTargetList', JSON.stringify(trustTargetList));
    }
  }

  function listenLocationReload() {
    document.addEventListener("visibilitychange", ()=> {
      const isFirstTrust = sessionStorage.getItem('isFirstTrust');
      if (document.visibilityState === 'visible' && isFirstTrust === 'true') {
        location.reload();
        sessionStorage.setItem('isFirstTrust', 'false');
      }
    })
  }

  function closeTrustModal() {
    const trustModal = document.getElementById('trustModal');
    trustModal.style.display = 'none';
  }
</script>
</body>

</html>
